<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\Validate;

/**
 * 公司信息
 *
 * @icon fa fa-circle-o
 */
class Company extends Backend
{
    /**
     * Company模型对象
     * @var \app\common\model\Company
     */
    protected $model = null;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Company;
        $this->view->assign("identificationswitchList", $this->model->getIdentificationswitchList());
        $this->view->assign("managementList", $this->model->getManagementList());
        Hook::add('admin_auth','app\\admin\\behavior\\AdminAuth');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $where_company = [];
        if($this->auth->type == 2){
            $company_id_array = model('admin/dealer/DealerCompany')->getCompanyIds($this->auth->type_id);
            $where_company['id'] = array('in', $company_id_array);
        }

        $dealer_id = $this->request->param('dealer_id');
        if($dealer_id){
            $company_id_array = model('admin/dealer/DealerCompany')->getCompanyIds($dealer_id);
            $where_company['id'] = array('in', $company_id_array);
        }
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField') && $dealer_id == 0)
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->where($where)
                    ->where($where_company)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->where($where_company)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','name','concat_phone','code','createtime', 'admin_id']);
                //获取管理员账号id
                $admin_id = Db::name('admin')->where(['type' => 1, 'type_id'=> $row['id']])->value('id');
                $row['admin_id'] = $admin_id;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $statisticsModel = model('Statistics');
        //总数
        $total_company = $statisticsModel->countCompany();
        $this->view->assign('total_company', $total_company);
        //今日新增数量
        $start_time_today = strtotime(date('Y-m-d'));
        $end_time_today = strtotime(date('Y-m-d').'+1 day') - 1;
        $where_today_company['createtime'] = array('between', array($start_time_today, $end_time_today));
        $total_company_today = $statisticsModel->countCompany($where_today_company);
        //本周新增
        $timestamp = time();
        $start_time_weekly = strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
        $end_time_weekly = strtotime(date('Y-m-d', strtotime("next week Monday", $timestamp)))  - 1;
        $where_weekly_company['createtime'] = array('between', array($start_time_weekly, $end_time_weekly));
        $total_company_weekly = $statisticsModel->countCompany($where_weekly_company);
        //本月新增
        $start_time_month = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $end_time_month = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $where_month_company['createtime'] = array('between', array($start_time_month, $end_time_month));
        $total_company_month = $statisticsModel->countCompany($where_month_company);

        $this->view->assign('total_company_today', $total_company_today);
        $this->view->assign('total_company_weekly', $total_company_weekly);
        $this->view->assign('total_company_month', $total_company_month);

        $this->view->assign('auth_type', $this->auth->type);

        return $this->view->fetch();
    }


    /**
     * 添加
     */
    /*public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {


                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    Db::startTrans();

                    $result = $this->model->allowField(true)->save($params);

                    if ($result !== false) {
                        $pinyin = Pinyin::get($params['name']);
                        $admin['username'] = substr($pinyin, 0, 6).''.$this->model->getLastInsID();
                        $admin['nickname'] = $params['name'];
                        $admin['email'] = $params['email'];
                        $admin['salt'] = Random::alnum();
                        $admin['password'] = md5(md5(123456) . $admin['salt']);
                        $admin['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                        $admin['company_id'] = $this->model->getLastInsID(); //设置新管理员默认头像。
                        $adminModel = new Admin();

                        try {
                            $res = $adminModel->validate('Admin.add')->data($admin)->isUpdate(false)->save();
                            if ($res === false) {
                                Db::rollback();
                                throw new Exception('保存信息出错');
                            }
                            //把用户加入权限组
                            Db::name('auth_group_access')->insert([
                                'uid' =>$adminModel->id,
                                'group_id' => config('site.company_auth_id') //定死的
                            ]);
                        } catch (\Exception $e) {
                            Db::rollback();
                            throw new Exception('保存信息出错');
                        }

                        Db::commit();
                        $this->success('保存成功');
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }*/

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $companyData = $this->model->toArray();
                    $companyData['type'] = 1; //企业类别
                    //生成账号 加入权限组
                    Hook::listen('admin_auth',$companyData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        Hook::add('admin_del','app\\admin\\behavior\\AdminAuth');
        //删除账号的同时 删除公司的账号
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                Db::startTrans();
                try {
                    $count += $v->delete();
                    //同时删除对应的账号
                    if ($v['id'] == 0) { //不能删除超级账号
                        continue;
                    }
                    $delParam = ['type' => 1, 'type_id' => $v['id']];
                    Hook::listen('admin_del', $delParam);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /*还原方法*/
    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $index => $item) {
                $count += $item->restore();
                $companyData = $item->toArray();
                $companyData['type'] = 1; //企业类别
                //生成账号 加入权限组
                Hook::listen('admin_auth',$companyData);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }


    /**修改管理员账号*/
    public function editAdmin($ids = null) {
        $admin = new Admin();
        $row = $admin->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    if(!Validate::is($params['password'], '\S{6,16}')){
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'email'    => 'email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
